from attr.filters import exclude

from config.exceptions import NotFoundError, BadRequestError
from models.role import Role
from repositories.permission_repositories import PermissionRepository
from repositories.role_repositories import RoleRepository
from schemas.users import RoleCreate, RoleUpdate, RolesResponse, RoleResponse


class RoleService:
    def __init__(self, role_repo: RoleRepository, permission_repo: PermissionRepository):
        self.role_repo = role_repo
        self.permission_repo = permission_repo


    def create_role(self, role_data: RoleCreate) -> Role:
        permissions_obj = []
        for permission_id in role_data.permissions:
            if not self.permission_repo.get_permission_obj_by_id(permission_id):
                raise NotFoundError(detail="权限不存在")
            permissions_obj.append(self.permission_repo.get_permission_obj_by_id(permission_id))

        role_data.permissions = permissions_obj

        if self.role_repo.get_role_by_name(role_data.name):
            raise BadRequestError(detail="角色名已存在")

        role_data = Role.model_validate(role_data)

        return self.role_repo.create_or_update_role(role_data)


    def delete_role(self, role_id: int):
        role = self.role_repo.get_role_by_id(role_id)
        if not role:
            raise NotFoundError(detail="角色不存在")
        self.role_repo.delete_role(role_id)
        return {"message": "删除成功"}

    def update_role(self, role_data: RoleUpdate) -> Role:
        role = self.role_repo.get_role_obj_by_id(role_data.id)
        if not role:
            raise NotFoundError(detail="角色不存在")
        permissions_obj = []
        for permission_id in role_data.permissions:
            if not self.permission_repo.get_permission_obj_by_id(permission_id):
                raise NotFoundError(detail="权限不存在")
            permissions_obj.append(self.permission_repo.get_permission_obj_by_id(permission_id))

        role_data.permissions = permissions_obj

        role.sqlmodel_update(role_data)
        return self.role_repo.create_or_update_role(role)


    def filter_roles(self, page: int | None, size: int | None) -> RolesResponse:
        return self.role_repo.filter_role(page, size)

    def get_role_by_id(self, role_id: int) -> RoleResponse:
        role = self.role_repo.get_role_by_id(role_id)
        if not role:
            raise NotFoundError(detail="角色不存在")
        return self.role_repo.get_role_by_id(role_id)
